#include "mainwindow.h"
#include <QFileDialog>
#include <QPlainTextEdit>
#include <QTabWidget>
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    createActions();
}


MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::open()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"));
    if (fileName == "")
        return;

    QFile file(fileName);
    if (file.open(QFile::ReadOnly | QFile::Text))
    {
        QPlainTextEdit *ed = new QPlainTextEdit;
        ed->setPlainText(file.readAll());
        ed->setFont(QFont("Courier", 10));

        ui->textTabs->addTab(ed, fileName);
        ui->textTabs->setCurrentWidget(ed);
    }
}

void MainWindow::close(int index)
{
    ui->textTabs->removeTab(index);
    delete ui->textTabs->widget(index);
}

void MainWindow::createActions()
{
    // Create actions
    QAction *openAct = new QAction(tr("&Open..."), this);
    openAct->setShortcut(QKeySequence(tr("Ctrl+O")));
    openAct->setStatusTip(tr("Open an existing file"));
    connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

    connect(ui->textTabs, SIGNAL(tabCloseRequested(int)), this, SLOT(close(int)));

    // Assign icons to actions
    QIcon openIcon("icons/open_8bit.ico");
    openAct->setIcon(openIcon);
    openAct->setVisible(true);
    openAct->setIconVisibleInMenu(true);

    // Add actions to menus
    ui->menuFile->addAction(openAct);

    // Add actions to tool bar
    ui->mainToolBar->setIconSize(QSize(16,16));
    ui->mainToolBar->addAction(openAct);
    
    // Configure tabbed container in MDI area
    ui->textTabs->setTabsClosable(true);
}
